<!-- src/views/bis/exam/group/index.vue -->
<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="我负责的" name="mainOwner"></el-tab-pane>
      <el-tab-pane label="我参与的" name="secondaryOwner"></el-tab-pane>
      <el-tab-pane label="我加入的" name="member"></el-tab-pane>
      <el-tab-pane label="已禁用/退出" name="disabledOrQuit"></el-tab-pane>
      <el-tab-pane label="申请记录" name="applications"></el-tab-pane>
      <el-tab-pane label="待处理邀请" name="pendingInvites">
        <span slot="label">
          待处理邀请<el-badge v-if="pendingCount > 0" :value="pendingCount" class="item"></el-badge>
        </span>
      </el-tab-pane>
    </el-tabs>

    <!-- 搜索区域 -->
    <el-row :gutter="20" class="mb10">
      <el-col :span="6">
        <el-input v-model="queryParams.searchKey" placeholder="输入邀请码" clearable @keyup.enter.native="handleSearchByCode">
          <el-button slot="append" icon="el-icon-search" @click="handleSearchByCode"></el-button>
        </el-input>
      </el-col>
      <el-col :span="18" class="text-right">
        <el-button type="primary" icon="el-icon-plus" @click="handleCreate">新建考试组</el-button>
      </el-col>
    </el-row>

    <!-- 邀请码搜索结果对话框 -->
    <el-dialog
      title="申请加入考试组"
      :visible.sync="inviteDialogVisible"
      width="30%"
      center
    >
      <div v-if="searchedGroup">
        <el-card :body-style="{ padding: '0px' }" shadow="hover">
          <img :src="searchedGroup.coverImage || require('@/assets/images/login-background.jpg')" class="image"/>
          <div style="padding: 14px;">
            <div class="group-title">{{ searchedGroup.name }}</div>
            <div class="group-desc">{{ searchedGroup.description || '暂无描述' }}</div>
            <div class="group-footer">
              <span class="group-owner">主要负责人: {{ searchedGroup.mainOwnerName }}</span>
              <span class="group-time">创建时间: {{ formatTime(searchedGroup.createTime) }}</span>
            </div>
          </div>
        </el-card>
        <div style="margin-top: 20px; text-align: center;">
          <el-button type="primary" @click="handleApplyJoin">申请加入</el-button>
          <el-button @click="inviteDialogVisible = false">取消</el-button>
        </div>
      </div>
      <div v-else style="text-align: center;">
        <p>未找到对应的考试组，请检查邀请码是否正确</p>
        <el-button @click="inviteDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 考试组卡片列表 -->
    <div v-if="activeTab !== 'applications' && activeTab !== 'pendingInvites'">
      <el-row :gutter="20">
        <el-col
          v-for="group in groupList"
          :key="group.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
        >
          <el-card
            :body-style="{ padding: '0px' }"
            :class="{'disabled-card': group.status === 0 || group.status !== 1}"
            class="group-card"
            shadow="hover"
            @click.native="handleCardClick(group)"
            @mouseenter.native="hoverCard = group.id"
            @mouseleave.native="hoverCard = null"
          >
            <img :src="group.coverImage || require('@/assets/images/login-background.jpg')" class="image"/>
            <div style="padding: 14px;">
              <div class="group-title">{{ group.name }}</div>
              <div class="group-desc">{{ group.description || '暂无描述' }}</div>
              <div class="group-footer">
                <span class="group-role">{{ formatRole(group.role) }}</span>
                <span class="group-time">{{ formatTime(group.createTime) }}</span>
                <el-tag
                  v-if="group.status !== 1"
                  :type="getStatusTagType(group.status)"
                  size="mini"
                  class="status-tag"
                >
                  {{ getStatusText(group.status) }}
                </el-tag>
              </div>

              <!-- 操作按钮 -->
              <div v-show="hoverCard === group.id" class="group-actions" @click.stop>
                <template v-if="activeTab === 'mainOwner'">
                  <el-button type="text" @click="handleEdit(group)">编辑</el-button>
                  <el-button type="text" @click="handleTransfer(group)">移交</el-button>
                  <el-button type="text" @click="handleEnable(group, false)" v-if="group.status === 1">禁用</el-button>
                  <el-button type="text" @click="handleEnable(group, true)" v-else>启用</el-button>
                  <el-button type="text" @click="handleDelete(group)">删除</el-button>
                </template>

                <template v-else-if="activeTab === 'secondaryOwner'">
                  <el-button type="text" @click="handleQuit(group)">退出</el-button>
                </template>

                <template v-else-if="activeTab === 'member'">
                  <el-button type="text" @click="handleQuit(group)">退出</el-button>
                </template>

                <template v-else-if="activeTab === 'disabledOrQuit'">
                  <el-button v-if="group.status === 0" type="text" @click="handleEnable(group, true)">启用</el-button>
                  <el-button v-else type="text" @click="handleRejoin(group)">重新加入</el-button>
                </template>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 申请记录表格 -->
    <div v-else-if="activeTab === 'applications'">
      <el-table :data="applicationList" style="width: 100%">
        <el-table-column prop="groupName" label="考试组名称" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.groupName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="mainOwnerName" label="主要负责人" width="120"></el-table-column>
        <el-table-column prop="createTime" label="申请时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.approveStatus)">
              {{ getStatusText(scope.row.approveStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.approveStatus === 0"
              type="text"
              @click="handleCancelApplication(scope.row)"
            >取消申请</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="applicationTotal > 0"
        :total="applicationTotal"
        :page.sync="applicationQuery.pageNum"
        :limit.sync="applicationQuery.pageSize"
        @pagination="getApplicationList"
      />
    </div>

    <!-- 待处理邀请表格 -->
    <div v-else-if="activeTab === 'pendingInvites'">
      <el-table :data="inviteList" style="width: 100%">
        <el-table-column prop="groupName" label="考试组名称" width="180"></el-table-column>
        <el-table-column prop="inviterName" label="邀请人" width="120"></el-table-column>
        <el-table-column prop="createTime" label="邀请时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleAccept(scope.row)">接受</el-button>
            <el-button type="danger" size="small" @click="handleReject(scope.row)">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="inviteTotal > 0"
        :total="inviteTotal"
        :page.sync="inviteQuery.pageNum"
        :limit.sync="inviteQuery.pageSize"
        @pagination="getInviteList"
      />
    </div>

    <!-- 分页 -->
    <pagination
      v-show="total > 0 && activeTab !== 'applications' && activeTab !== 'pendingInvites'"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新建/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="考试组名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入考试组名称"></el-input>
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImage">
          <el-upload
            class="avatar-uploader"
            action="/file/upload/public"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.coverImage" :src="form.coverImage" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">建议尺寸800x400，大小不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="最大分组数" prop="maxSubgroups">
          <el-input-number v-model="form.maxSubgroups" :min="1" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入描述信息"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 移交对话框 -->
    <el-dialog title="移交主要负责权限" :visible.sync="transferDialogVisible" width="40%">
      <el-form>
        <el-form-item label="选择新负责人">
          <el-select v-model="transferForm.newOwnerId" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="member in secondaryOwners"
              :key="member.userId"
              :label="member.userName"
              :value="member.userId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="transferDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTransfer">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getMainOwnerGroups,
  getSecondaryOwnerGroups,
  getMemberGroups,
  getDisabledOrQuitGroups,
  getPendingInvites,
  getStudentApplications,
  searchGroupByCode,
  applyJoinGroup,
  handleInvite,
  transferOwnership,
  quitGroup,
  enableGroup,
  deleteGroup,
  addExamGroup,
  updateExamGroup,
  cancelApplication
} from '@/api/exam/group'
import { parseTime } from "@/utils/quiz"

export default {
  name: 'ExamGroup',
  data() {
    return {
      activeTab: 'mainOwner',
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        searchKey: ''
      },
      applicationQuery: {
        pageNum: 1,
        pageSize: 10
      },
      inviteQuery: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      applicationTotal: 0,
      inviteTotal: 0,
      groupList: [],
      applicationList: [],
      inviteList: [],
      hoverCard: null,
      pendingCount: 0,
      inviteDialogVisible: false,
      searchedGroup: null,

      // 对话框相关
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        name: '',
        coverImage: '',
        description: '',
        maxSubgroups: 10
      },
      rules: {
        name: [
          {required: true, message: '请输入考试组名称', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
        description: [
          {max: 500, message: '不能超过 500 个字符', trigger: 'blur'}
        ],
        maxSubgroups: [
          {type: 'number', min: 1, max: 100, message: '取值范围 1-100', trigger: 'blur'}
        ]
      },

      // 移交相关
      transferDialogVisible: false,
      transferForm: {
        groupId: null,
        newOwnerId: null
      },
      secondaryOwners: []
    }
  },
  created() {
    this.getList()
    this.getApplicationList()
    this.getInviteList()
  },
  methods: {
    handleCardClick(group) {
      if (group.status === 0 || group.status !== 1) return
      this.$router.push({
        path: '/exam/group/participants',
        name: 'ExamGroupDetail',
        params: { groupId: group.id }
      })
    },

    getList() {
      let apiMethod
      switch (this.activeTab) {
        case 'mainOwner':
          apiMethod = getMainOwnerGroups
          break
        case 'secondaryOwner':
          apiMethod = getSecondaryOwnerGroups
          break
        case 'member':
          apiMethod = getMemberGroups
          break
        case 'disabledOrQuit':
          apiMethod = getDisabledOrQuitGroups
          break
        default:
          apiMethod = getMainOwnerGroups
      }

      apiMethod(this.queryParams).then(response => {
        this.groupList = response.rows
        this.total = response.total
      })
    },

    getApplicationList() {
      getStudentApplications(this.applicationQuery).then(response => {
        this.applicationList = response.rows
        this.applicationTotal = response.total
      })
    },

    getInviteList() {
      getPendingInvites(this.inviteQuery).then(response => {
        this.inviteList = response.rows
        this.inviteTotal = response.total
        this.pendingCount = response.total
      })
    },

    handleTabChange(tab) {
      this.queryParams.pageNum = 1
      if (tab.name === 'applications') {
        this.getApplicationList()
      } else if (tab.name === 'pendingInvites') {
        this.getInviteList()
      } else {
        this.getList()
      }
    },

    handleSearchByCode() {
      if (!this.queryParams.searchKey) {
        this.$message.warning('请输入邀请码')
        return
      }

      searchGroupByCode(this.queryParams.searchKey).then(response => {
        this.searchedGroup = response.data
        this.inviteDialogVisible = true
      }).catch(() => {
        this.searchedGroup = null
        this.inviteDialogVisible = true
      })
    },

    handleApplyJoin() {
      if (!this.searchedGroup) return

      applyJoinGroup({
        groupId: this.searchedGroup.id,
        inviteCode: this.queryParams.searchKey
      }).then(() => {
        this.$message.success('申请已提交，等待审核')
        this.inviteDialogVisible = false
        this.queryParams.searchKey = ''
        this.getApplicationList()
      })
    },

    handleCreate() {
      this.dialogTitle = '新建考试组'
      this.resetForm()
      this.dialogVisible = true
    },

    handleEdit(group) {
      this.dialogTitle = '编辑考试组'
      this.form = {...group}
      this.dialogVisible = true
    },

    handleTransfer(group) {
      this.transferForm.groupId = group.id
      this.getSecondaryOwners(group.id)
      this.transferDialogVisible = true
    },

    handleQuit(group) {
      this.$confirm('确定要退出该考试组吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        quitGroup(group.id).then(() => {
          this.$message.success('退出成功')
          this.getList()
        })
      })
    },

    handleEnable(group, enable) {
      const action = enable ? '启用' : '禁用'
      this.$confirm(`确定要${action}该考试组吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        enableGroup(group.id, enable).then(() => {
          this.$message.success(`${action}成功`)
          this.getList()
        })
      })
    },

    handleDelete(group) {
      this.$confirm('确定要删除该考试组吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteGroup(group.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },

    handleAccept(invite) {
      handleInvite(invite.id, true).then(() => {
        this.$message.success('已接受邀请')
        this.getInviteList()
        this.getList()
      })
    },

    handleReject(invite) {
      handleInvite(invite.id, false).then(() => {
        this.$message.success('已拒绝邀请')
        this.getInviteList()
      })
    },

    handleRejoin(group) {
      applyJoinGroup(group.inviteCode).then(() => {
        this.$message.success('已发送加入申请')
      })
    },

    handleCancelApplication(application) {
      this.$confirm('确定要取消该申请吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelApplication(application.id).then(() => {
          this.$message.success('取消申请成功')
          this.getApplicationList()
        })
      })
    },

    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const isAdd = this.dialogTitle === '新建考试组'
          const apiMethod = isAdd ? addExamGroup : updateExamGroup

          const formData = {
            id: this.form.id,
            name: this.form.name,
            coverImage: this.form.coverImage,
            description: this.form.description,
            maxSubgroups: this.form.maxSubgroups
          }

          apiMethod(formData).then(() => {
            this.$message.success(isAdd ? '创建成功' : '修改成功')
            this.dialogVisible = false
            this.getList()
          })
        }
      })
    },

    submitTransfer() {
      if (!this.transferForm.newOwnerId) {
        this.$message.warning('请选择新负责人')
        return
      }

      transferOwnership(this.transferForm.groupId, this.transferForm.newOwnerId).then(() => {
        this.$message.success('移交成功')
        this.transferDialogVisible = false
        this.getList()
      })
    },

    getSecondaryOwners(groupId) {
      // 模拟获取次要负责人
      this.secondaryOwners = [
        {userId: 2, userName: '张老师'},
        {userId: 3, userName: '李老师'}
      ]
    },

    resetForm() {
      this.form = {
        id: null,
        name: '',
        coverImage: '',
        description: '',
        maxSubgroups: 10
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    formatRole(role) {
      const roles = {
        1: '主要负责人',
        2: '次要负责人',
        3: '考生'
      }
      return roles[role] || '未知角色'
    },

    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已拒绝',
        3: '已退出'
      }
      return statusMap[status] || '未知状态'
    },

    getStatusTagType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger',
        3: 'info'
      }
      return typeMap[status] || ''
    },

    formatTime(time) {
      return parseTime(time, '{y}-{m}-{d}')
    },

    handleAvatarSuccess(response, file) {
      if (response.code === 200) {
        this.form.coverImage = response.data
      } else {
        this.$message.error('上传失败')
      }
    },

    beforeAvatarUpload(file) {
      const isImage = /^image\/(jpeg|png|gif)$/.test(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    }
  }
}
</script>

<style scoped>
.group-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  position: relative;
}

.group-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.disabled-card {
  opacity: 0.6;
  cursor: not-allowed;
}

.disabled-card:hover {
  transform: none;
  box-shadow: none;
}

.image {
  width: 100%;
  height: 160px;
  object-fit: cover;
  display: block;
}

.group-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.group-desc {
  font-size: 12px;
  color: #999;
  height: 36px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.group-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 12px;
  color: #666;
  align-items: center;
}

.group-role {
  background-color: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
}

.group-actions {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.9);
  padding: 5px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  pointer-events: none;
}

.group-actions button {
  pointer-events: auto;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.status-tag {
  margin-left: 8px;
}

.group-owner {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.el-table {
  margin-top: 20px;
}
</style>
